<?php
require_once(PATH_t3lib . 'class.t3lib_pagetree.php');

class ux_tx_ttnews extends tx_ttnews {

	/**
	 * Find related news records and pages, add links to them and wrap them with stdWraps from TS.
	 *
	 * @param	integer		$uid of the current news record
	 * @return	string		html code for the related news list
	 */
	function getRelated($uid) {
	
		$lConf = $this->conf['getRelatedCObject.'];

		if ($this->conf['checkCategoriesOfRelatedNews'] || $this->conf['useSPidFromCategory']) {
			// get visible categories and their singlePids
			$catres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tt_news_cat.uid,tt_news_cat.single_pid', 'tt_news_cat', '1=1' . $this->SPaddWhere . $this->enableCatFields);

			$catTemp = array();
			$sPidByCat = array();
			while (($catrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($catres))) {
				$sPidByCat[$catrow['uid']] = $catrow['single_pid'];
				$catTemp[] = $catrow['uid'];
			}
			$GLOBALS['TYPO3_DB']->sql_free_result($catres);
			if ($this->conf['checkCategoriesOfRelatedNews']) {
				$visibleCategories = implode($catTemp, ',');
			}
		}

		if ($this->conf['usePagesRelations']) {
			$relPages = $this->getRelatedPages($uid);
		}
		//		$select_fields = 'DISTINCT uid, pid, title, short, datetime, archivedate, type, page, ext_url, sys_language_uid, l18n_parent, M.tablenames';
		$select_fields = ' uid, pid, title, short, datetime, archivedate, type, page, ext_url, sys_language_uid, l18n_parent, tt_news_related_mm.tablenames';

		//		$where = 'tt_news.uid=M.uid_foreign AND M.uid_local=' . $uid . ' AND M.tablenames!=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('pages', 'tt_news_related_mm');
		$where = 'tt_news_related_mm.uid_local=' . $uid . '
					AND tt_news.uid=tt_news_related_mm.uid_foreign
					AND tt_news_related_mm.tablenames!=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('pages', 'tt_news_related_mm');

		if ($lConf['groupBy']) {
			$groupBy = trim($lConf['groupBy']);
		}
		if ($lConf['orderBy']) {
			$orderBy = trim($lConf['orderBy']);
		}

		if ($this->conf['useBidirectionalRelations']) {
			//			$where = '((' . $where . ') OR (tt_news.uid=M.uid_local AND M.uid_foreign=' . $uid . ' AND M.tablenames!=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('pages', 'tt_news_related_mm') . '))';


			$where = '((' . $where . ')
					OR (tt_news_related_mm.uid_foreign=' . $uid . '
						AND tt_news.uid=tt_news_related_mm.uid_local
						AND tt_news_related_mm.tablenames!=' . $GLOBALS['TYPO3_DB']->fullQuoteStr('pages', 'tt_news_related_mm') . '))';
		}

		//		$from_table = 'tt_news,tt_news_related_mm AS M';
		$from_table = 'tt_news_related_mm, tt_news';
		
		//////////////////
		$related_access_pid=array();
		$add_access='';
		
		
		if($this->conf['related_access']==1)
		{
			if(stristr($this->conf['related_access_pid'],',')) $treeStartingPoint=explode(',',$this->conf['related_access_pid']);
			else $treeStartingPoint=array(intval($this->conf['related_access_pid']));
			
			for($i=0; $i<count($treeStartingPoint); $i++)
			{
				if($this->conf['related_access_depth']!=0) $related_access_pid=array_merge($related_access_pid,$this->get_treeID($treeStartingPoint[$i],$this->conf['related_access_depth']));
				else $related_access_pid[]=$treeStartingPoint[$i];
			}
			$add_access='AND tt_news.pid NOT IN ('.implode(',',$related_access_pid).')';
		}

		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($select_fields, $from_table, $where . $this->enableFields.$add_access, $groupBy, $orderBy);

		if ($res) {
			$relrows = array();
			while (($relrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))) {

				$currentCats = array();
				if ($this->conf['checkCategoriesOfRelatedNews'] || $this->conf['useSPidFromCategory']) {
					$currentCats = $this->getCategories($relrow['uid'], true);
				}
				if ($this->conf['checkCategoriesOfRelatedNews']) {
					if (count($currentCats)) { // record has categories
						foreach ($currentCats as $cUid) {
							if (t3lib_div::inList($visibleCategories, $cUid['catid'])) { // if the record has at least one visible category assigned it will be shown
								$relrows[$relrow['uid']] = $relrow;
								break;
							}
						}
					} else { // record has NO categories
						$relrows[$relrow['uid']] = $relrow;
					}
				} else {
					$relrows[$relrow['uid']] = $relrow;
				}

				// check if there's a single pid for the first category of a news record and add 'sPidByCat' to the $relrows array.
				if ($this->conf['useSPidFromCategory'] && count($currentCats) && $relrows[$relrow['uid']]) {
					$firstcat = array_shift($currentCats);
					if ($firstcat['catid'] && $sPidByCat[$firstcat['catid']]) {
						$relrows[$relrow['uid']]['sPidByCat'] = $sPidByCat[$firstcat['catid']];
					}
				}
			}
			//			debug($relrows, '$relrows ('.__CLASS__.'::'.__FUNCTION__.')', __LINE__, __FILE__, 3);


			$GLOBALS['TYPO3_DB']->sql_free_result($res);
			if (is_array($relPages[0]) && $this->conf['usePagesRelations']) {
				$relrows = array_merge_recursive($relPages, $relrows);
			}

			$piVarsArray = array('backPid' => ($this->conf['dontUseBackPid'] ? null : $this->config['backPid']),
					'year' => ($this->conf['dontUseBackPid'] ? null : ($this->piVars['year'] ? $this->piVars['year'] : null)),
					'month' => ($this->conf['dontUseBackPid'] ? null : ($this->piVars['month'] ? $this->piVars['month'] : null)));

			$veryLocal_cObj = t3lib_div::makeInstance('tslib_cObj'); // Local cObj.
			$lines = array();

			// save current realUrl state
			$tmpRealUrl = (bool) $GLOBALS['TSFE']->config['config']['tx_realurl_enable'];
			$tmpCoolUri = (bool) $GLOBALS['TSFE']->config['config']['tx_cooluri_enable'];

			foreach ($relrows as $row) {
				if ($GLOBALS['TSFE']->sys_language_content && $row['tablenames'] != 'pages') {
					$OLmode = ($this->sys_language_mode == 'strict' ? 'hideNonTranslated' : '');
					$row = $GLOBALS['TSFE']->sys_page->getRecordOverlay('tt_news', $row, $GLOBALS['TSFE']->sys_language_content, $OLmode);
					if (! is_array($row))
						continue;
				}
				$veryLocal_cObj->start($row, 'tt_news');

				if ($row['type'] != 1 && $row['type'] != 2) { // only normal news
					$catSPid = false;
					if ($row['sPidByCat'] && $this->conf['useSPidFromCategory']) {
						$catSPid = $row['sPidByCat'];
					}
					$sPid = ($catSPid ? $catSPid : $this->config['singlePid']);

					// temporary disable realUrl to get raw GETvars from function getSingleViewLink()
					$GLOBALS['TSFE']->config['config']['tx_realurl_enable'] = 0;
					$GLOBALS['TSFE']->config['config']['tx_cooluri_enable'] = 0;

					// special treatment for simulatestatic because it doesn't seem possible to temporarily disable it after tslib_fe is once initialized
					if ($GLOBALS['TSFE']->config['config']['simulateStaticDocuments']) {

					/**
					 * TODO: 16.04.2009
					 *
					 * extract parameters from GETvars like it was done in tt_news 2.5.x
					 */

					}

					$link = $this->getSingleViewLink($sPid, $row, $piVarsArray, true);

					$linkArr = t3lib_div::explodeUrl2Array($link, true);

					if (is_array($linkArr) && is_array($linkArr['tx_ttnews'])) {
						$newsAddParams = t3lib_div::implodeArrayForUrl('tx_ttnews', $linkArr['tx_ttnews']);
					}

					// load the parameter string into the register 'newsAddParams' to access it from TS
					$veryLocal_cObj->LOAD_REGISTER(array('newsAddParams' => $newsAddParams, 'newsSinglePid' => $sPid), '');

					if (! $this->conf['getRelatedCObject.']['10.']['default.']['10.']['typolink.']['parameter'] || $catSPid) {
						$this->conf['getRelatedCObject.']['10.']['default.']['10.']['typolink.']['parameter'] = $sPid;
					}
				}
				// re-enable realUrl (if set) to make cObjGetSingle render the related links as realUrls
				$GLOBALS['TSFE']->config['config']['tx_realurl_enable'] = $tmpRealUrl;
				$GLOBALS['TSFE']->config['config']['tx_cooluri_enable'] = $tmpCoolUri;
				$lines[] = $veryLocal_cObj->cObjGetSingle($this->conf['getRelatedCObject'], $this->conf['getRelatedCObject.'], 'getRelatedCObject');
			}
			// make sure that realUrl is set to its previous state
			$GLOBALS['TSFE']->config['config']['tx_realurl_enable'] = $tmpRealUrl;
			$GLOBALS['TSFE']->config['config']['tx_cooluri_enable'] = $tmpCoolUri;

			if ($this->debugTimes) {
				$this->hObj->getParsetime(__METHOD__);
			}

			return implode('', $lines);
		}
	}
	function get_treeID($treeStartingPoint,$depth)
	{
		$treeStartingRecord = t3lib_BEfunc::getRecord('pages', $treeStartingPoint);
		$tree = t3lib_div::makeInstance('t3lib_pageTree');
		$tree->init('AND ' . 1);
		$tree->getTree($treeStartingPoint, $depth, '');
		return $tree->ids;
	}	
	

}
?>